﻿//==============================================================================
//  File Name   :   GalleryAlbumItem.cs
//
//  Copyright © 2007 by Do Hong Ngoc. All rights reserved.
//
//  Distributable under GPL code license.
//  See terms of license at www.bbquyen.com.
//
//==============================================================================

// <fileinformation>
//   <summary>
//     This file defines the GalleryAlbumItem class.
//   </summary>
//   <author name="Do Hong Ngoc" mail="whiterose1611vn@yahoo.co.uk"/>
//   <date>3/31/2007 10:51:20 AM</date>
//   <remarks>
//     
//   </remarks>
// </fileinformation>

using System;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using BbqFramework.Web.UI.Controls;
using BbqFramework.Web.UI;

namespace Bbq.Gallery.UI
{
	/// <summary>
	/// Defines GalleryAlbumItem class.
	/// </summary>
	[ToolboxItem(false)]
    public class GalleryAlbumItemRenderer : WebControlBase, INamingContainer, ISupportCustomContextMenu
	{
		#region Constants
        /// <summary>
        /// Default width of album item
        /// </summary>
        internal const int DEFAULT_WIDTH = 149;
		private const string CUSTOM_CONTEXT_MENU_ID = "Pic";
		#endregion

		#region Private Fields
		private GalleryItem _galleryItem = null;
		#endregion

		#region Public Protected Properties
		#endregion

		#region Internal Private Properties
		#endregion

		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="GalleryAlbumItem"/> class.
		/// </summary>
		public GalleryAlbumItemRenderer(GalleryItem galleryItem)
			: base(HtmlTextWriterTag.Div)
		{
			this.EnableViewState = false;

			//Initialization for default gallery item
            this.Width = Unit.Pixel(DEFAULT_WIDTH);
			this.Height = Unit.Pixel(140);
			this.Style.Add("float", "left");
			this.Style.Add(HtmlTextWriterStyle.Padding, "5px 5px 5px 5px");

			//Data
			_galleryItem = galleryItem;
		}
		#endregion

		#region Override Functions
		/// <summary>
		/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
		/// </summary>
		protected override void CreateChildControls()
		{
			//Ensure that each control will be displayed one time
			this.Controls.Clear();

			ClientScriptManager clientScript = this.Page.ClientScript;

			UpdatePanel uPanel = new UpdatePanel();
			uPanel.ID = "UP";
			uPanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
			this.Controls.Add(uPanel);

			Literal albumRenderText = new Literal();
			albumRenderText.ID = "albumRenderText";
			albumRenderText.Text = BuildAlbumItem();
			uPanel.ContentTemplateContainer.Controls.Add(albumRenderText);

			PlaceHolder editArea = new PlaceHolder();
			editArea.ID = "editArea";
			//editArea.Style[HtmlTextWriterStyle.Display] = "none";
			uPanel.ContentTemplateContainer.Controls.Add(editArea);
			LiteralControl divEditArea = new LiteralControl();
			divEditArea.ID = "divEditArea";
			editArea.Controls.Add(divEditArea);
			divEditArea.Text = string.Concat("<div style=\"display: none; padding-left: 17px;\" id=\"", divEditArea.ClientID, "\">");

			Panel descControl = new Panel();
			descControl.ID = "descControl";
			descControl.Style[HtmlTextWriterStyle.PaddingLeft] = "17px";
			uPanel.ContentTemplateContainer.Controls.Add(descControl);
			descControl.Attributes["ondblclick"] = string.Concat("__bbqGallery_RenameGalleryItem(false, '", divEditArea.ClientID, "','", descControl.ClientID, "');");
            descControl.Attributes["unselectable"] = "on";
            descControl.Style["-moz-user-select"] = "none";
            descControl.Attributes["onselectstart"] = "return false;";
            LiteralControl itemName = new LiteralControl(_galleryItem.Name);
			itemName.ID = "itemName";
			descControl.Controls.Add(itemName);

			TextBox txtItemName = new TextBox();
			txtItemName.Style[HtmlTextWriterStyle.PaddingLeft] = "2px";
			txtItemName.ID = "txtItemName";
			txtItemName.Text = _galleryItem.Name;
			txtItemName.Columns = 12;
			editArea.Controls.Add(txtItemName);

			Button ibChangeItemName = new Button();
			ibChangeItemName.Text = "Save";
			ibChangeItemName.EnableViewState = false;
			ibChangeItemName.ID = "ibChangeItemName";
			ibChangeItemName.OnClientClick = "__bbqGallery_RenameGalleryItem(true,null,null,this);";
			//ibChangeItemName.ImageUrl = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.ok.gif");
			ibChangeItemName.Click += ibChangeItemName_Click;
			editArea.Controls.Add(ibChangeItemName);

			LiteralControl endDiv = new LiteralControl("</div>");
			editArea.Controls.Add(endDiv);

			HiddenField idItem = new HiddenField();
			idItem.ID = "idItem";
			idItem.Value = GalleryHelper.ResolveItemIdentity(_galleryItem);
			uPanel.ContentTemplateContainer.Controls.Add(idItem);
		}

		/// <summary>
		/// Raises the <see cref="E:System.Web.UI.Control.PreRender"></see> event.
		/// </summary>
		/// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			ClientScriptManager clientScript = this.Page.ClientScript;
			//Register CSS
			object obj = this.Page.Items["BBQGallery_ItemCss"];
			if (obj == null)
			{
				this.Page.Items["BBQGallery_ItemCss"] = true;
				string urlCSS = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.FuzzyShadows.css");
				string urlCSSIE55 = clientScript.GetWebResourceUrl(typeof(Gallery), "Bbq.Gallery.Resource.Theme.Default.FuzzyShadowsIE55.css");
				Literal cssCtrl = new Literal();
				cssCtrl.Text = @"
<style type=""text/css"">@import url(""" + urlCSS + @""");</style>
<!--[if gte ie 5.5000]>
<style type=""text/css"">@import url(""" + urlCSSIE55 + @""");</style>
<![endif]-->";
				this.Page.Header.Controls.Add(cssCtrl);
			}
		}
		#endregion

		#region Private Functions
		/// <summary>
		/// Handles the Click event of the ibChangeItemName control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		void ibChangeItemName_Click(object sender, EventArgs e)
		{
			GalleryProvider provider = Gallery.GalleryProvider;
			UpdatePanel uPanel = (UpdatePanel)this.Controls[0];
			string newName = (uPanel.FindControl("txtItemName") as TextBox).Text;
			HiddenField idItem = (uPanel.FindControl("idItem") as HiddenField);
			string id = idItem.Value;
			_galleryItem = provider.GetGalleryItemInfo(provider.GetActualItemIdentity(id));
			GalleryItem oldItem = (GalleryItem)_galleryItem.Clone();
			_galleryItem.Name = newName;
			provider.UpdateGalleryItem(oldItem, _galleryItem);
			Panel descItemName = uPanel.FindControl("descControl") as Panel;
			LiteralControl itemName = descItemName.FindControl("itemName") as LiteralControl;
			itemName.Text = newName;
			idItem.Value = provider.ResolveItemIdentity(_galleryItem);

			Literal albumRenderText = uPanel.FindControl("albumRenderText") as Literal;
			albumRenderText.Text = BuildAlbumItem();
		}

		/// <summary>
		/// Builds the album item.
		/// </summary>
		/// <returns></returns>
        private string BuildAlbumItem()
        {
            ClientScriptManager clientScript = this.Page.ClientScript;
            StringBuilder sb = new StringBuilder();

			sb.Append("<div class=\"alpha-shadow\" id=\"");
			//This inner element will ClientID of GalleryAlbumItemRenderer
			sb.Append(this.ClientID + CUSTOM_CONTEXT_MENU_ID);
			sb.Append("\"><div>");
			sb.Append("<a href=\"");
            sb.Append(Gallery.GalleryProvider.ResolveItemLink(_galleryItem));
            sb.Append(@""" title=""");
            sb.Append(_galleryItem.Name);
            sb.Append(@""" rel=""lightbox[BbqGallery]""><img alt="""" src=""");
            sb.Append(Gallery.GalleryProvider.ResolveItemThumbnail(_galleryItem));
			sb.Append(@""" onmouseover=""__bbqGallery_ItemHover(this,'#dcdcdc','#6495ed',true)"" onmouseout=""__bbqGallery_ItemHover(this,'','',false)""/></a>");
			sb.Append("</div></div>");
			return sb.ToString();
        }

		#endregion

		#region Events
		#endregion


		#region ISupportCustomContextMenu Members

		/// <summary>
		/// Gets the target client id.
		/// </summary>
		/// <value>The target client id.</value>
		string ISupportCustomContextMenu.TargetClientId
		{
			get { return this.ClientID + CUSTOM_CONTEXT_MENU_ID; }
		}

		#endregion
	}
}
